package com.fulihui.wgj.admin.security.interceptor;

import com.fulihui.common.util.JedisUtil;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.config.properties.JwtProperties;
import com.fulihui.wgj.admin.security.jwt.JwtHelper;
import io.jsonwebtoken.Claims;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

import static com.fulihui.common.constants.JwtConstants.*;

/**
 * @author: Levon
 * @version: v 0.1 2018-06-14 16:43
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Setter
    private JwtProperties jwtProperties;

    @Setter
    private AdminProperties adminProperties;

    @Setter
    private JedisUtil jedisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object header) {

        String authHeader = request.getHeader(ACCESS_JWT_TOKEN);
        if (authHeader == null || !authHeader.startsWith(BEARER)) {
            return reLogin(response);
        }

        String appId = request.getHeader(APPID_KEY);
        if (StringUtils.isEmpty(appId)) {
            String requestURI = request.getRequestURI();
            if (StringUtils.isNotBlank(requestURI)) {
                if (requestURI.indexOf("platform/list") == -1) {
                    return reLogin(response);
                }
            }
        }

        String token = authHeader.substring(7);
        boolean exist = jedisUtil.exist(token);
        if (exist) {
            return reLogin(response);
        }

        Claims claims;
        try {
            claims = JwtHelper.parseJWT(token, jwtProperties.getBase64Secret());
        } catch (final Exception e) {
            return reLogin(response);
        }

        if (claims == null) {
            return reLogin(response);
        }

        Date expiration = claims.getExpiration();
        if (expiration.getTime() < System.currentTimeMillis()) {
            return reLogin(response);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private boolean reLogin(HttpServletResponse response) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }

}